<?php
namespace app\common\lib;
class Redis {
    private static $instance = null;
    private $redis = null;
    
    public static function getInstance() {
        /* if(empty(self::$instance)){
         self::$instance = new self();
         }
         
         return self::$instance; */
        return new self();
    }
    
    public function __construct() {
        $this->redis = new \Redis();
        $result = $this->redis->connect('47.74.10.165', 10301);
        if($result === false) {
            throw new \Exception('redis connect error');
        }
        
        $result = $this->redis->auth('bill123');
        if($result === false) {
            throw new \Exception('auth error');
        }
    }
    
    public function del($key) {
        return $this->redis->del($key);
    }
    
    public function set($key, $value, $expire = 0, $exists = 'nx') {
        if(is_array($value)){
            $value = json_encode($value);
        }
        
        if($expire > 0){
            return $this->redis->set($key, $value, [$exists, 'ex'=>$expire]);
        }else{
            return $this->redis->set($key, $value);
        }
    }
    
    public function setex($key, $value, $expire = 0) {
        if(is_array($value)){
            $value = json_encode($value);
        }
        
        if($expire <= 0){
            return false;
        }
        
        return $this->redis->setex($key, $expire, $value);
    }
    
    public function get($key) {
        return $this->redis->get($key);
    }
    
    public function mget(array $keys){
        return $this->redis->mget($keys);
    }
    
    public function lpush($key, $value) {
        if(is_array($value)){
            $value = json_encode($value);
        }
        return $this->redis->lPush($key, $value);
    }
    
    public function geoadd($key, $lng, $lat, $value) {
        if(is_array($value)){
            $value = json_encode($value);
        }
        return $this->redis->geoadd($key, $lng, $lat, $value);
    }
    
    public function sAdd($key, $value) {
        if(is_array($value)){
            $value = json_encode($value);
        }
        
        return $this->redis->sAdd($key, $value);
    }
    
    public function sRandMember($key, $count=1) {
        return $this->redis->sRandMember($key, $count);
    }
    
    public function handler() {
        return $this->redis;
    }
    
    public function close() {
        if($this->redis !== null){
            $this->redis->close();
            $this->redis = null;
        }
    }
    
    
}